package bar.dark.lee.setting.data;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;

import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.setting.TipInfoActivity;
import bar.dark.lee.setting.TipsActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;

public class DataOutActivity extends SuperActivity
{
	private View exportButton;
	
	private EditText fileNameEdit;
	
	private int dbCount = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.data_out_activity);
		
		setTitle("데이터 백업");
		
		setFindView();
		setClickListener();
		setData();
	}

	private void setFindView()
	{
		exportButton = findViewById(R.id.settingDataExportButton);
		fileNameEdit = (EditText) findViewById(R.id.settingDataExportName);
	}
	
	private void setData()
	{
		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH) + 1;
		int day = cal.get(Calendar.DAY_OF_MONTH);
		String time = cal.get(Calendar.HOUR) + "" + cal.get(Calendar.MINUTE) + "" + cal.get(Calendar.SECOND);
		
		String date = BDUtil.getDate(year, month, day);
		
		date = date.replace(" ", "");
		
		String fileName = DBSQLite.dataBaseName + date + "_" + time;
		
		fileNameEdit.setText(fileName);
	}
	
	private void setClickListener()
	{
		exportButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (fileNameEdit.getText().toString().equals(""))
				{
					BDUtil.showDialog(DataOutActivity.this, "확인", "파일이름을 입력해주세요.");
					return;
				}
				
				setDataExport();
			}
		});
	}
	
	private void setDataExport()
	{
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		
		dialog.setTitle("데이터백업");
		dialog.setIcon(android.R.drawable.ic_dialog_alert);
		dialog.setMessage("데이터를 백업 하시겠습니까?");
		
		dialog.setPositiveButton("백업", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				new ShowDialog().execute(0);
				dialog.dismiss();
			}
		});
		
		dialog.setNegativeButton("취소", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		});
		
		dialog.show();
	}
	
	private int setDataBackUp()
	{
		if (!isDataCheck())
		{
			return 3;
		}
		
		DBSQLite.getInstance(this).closeDatabese();
		
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try
		{
			File readfile = new File("/data/data/" 
					+ getPackageName() + "/" 
					+ DBSQLite.dataBaseName);
			
			if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
			{
				return 1;
			}
			
			fis = new FileInputStream(readfile);
			
			File directory = new File(Environment.getExternalStorageDirectory() + "/AccountBook");
			
			if (!directory.exists())
			{
				directory.mkdir();
			}
			
			File writefile = new File(directory + "/" + fileNameEdit.getText().toString() + ".db");
			
			fos = new FileOutputStream(writefile);
			
			byte [] buffer = new byte[1024];
			
			int bufBytes = 0;
			while ((bufBytes = fis.read(buffer)) != -1) 
			{
				fos.write(buffer, 0, bufBytes);
			}
			fos.flush();
			
		} catch (Exception e)
		{
			return 2;
		} finally {
			try
			{
				if (fis != null) fis.close();
				if (fos != null) fos.close();
				DBSQLite.getInstance(this);
			} catch (IOException e)
			{
				e.printStackTrace();
				return 2;
			}
		}
		
		return 0;
	}
	
	private boolean isDataCheck()
	{
		int count = 0;
		
		count += getDataCount("in_out");
		count += getDataCount("check_card");
		count += getDataCount("credit_card");
		count += getDataCount("bankbook");
		count += getDataCount("sms");
		count += getDataCount("auto_bank");
		count += getDataCount("auto_mybank");
		count += getDataCount("memo_main");
		count += getDataCount("budget_category");
		count += getDataCount("budget_in_category");
		count += getDataCount("budget_move_category");
		count += getDataCount("macro_list");
		
		if (count == 0)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	
	private int getDataCount(String tableName)
	{
		DBSQLite.getInstance(this).selectMapTile(superContext, 
				"SELECT * FROM " + tableName, new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				dbCount = c.getCount();
			}
		});
		
		return dbCount;
	}

	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		int flag = 0;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(DataOutActivity.this);
			dialog.setCancelable(false);
			dialog.setMessage("Loading...");
			dialog.show();
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0)
			{
				flag = setDataBackUp();
				return flag;
			}
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			dialog.dismiss();
			
			if (result != null)
			{
				if (result == 0)
				{
					BDUtil.showDialogFinish(DataOutActivity.this, "데이터백업", "데이터 백업이 완료 되었습니다.");
				}
				else if (result == 1)
				{
					BDUtil.showDialog(DataOutActivity.this, "에러", "SD카드가 없습니다.");
				}
				else if (result == 2)
				{
					BDUtil.showDialog(DataOutActivity.this, "데이터백업실패", "데이터 백업을 실패 하였습니다.");
				}
				else if (result == 3)
				{
					BDUtil.showDialog(DataOutActivity.this, "데이터백업실패", "백업할 데이터가 없습니다. 내역이나 자산을 입력을 해주세요.");
				}
			}
		}
	}

	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(this, TipInfoActivity.class);
		intent.putExtra(TipsActivity.TIP_REQUEST_KEY, TipsActivity.TIP_DATABANKUP);
		startActivity(intent);
	}
}
